import { defineStore } from 'pinia'
import { ref } from 'vue';
import { Camera } from '@capacitor/camera';
import { useCategoryStore } from './categoryStore';


export const useEmojiStore = defineStore(
  'emoji',
  // 组合式逻辑（第一个函数参数）
  () => {
    const emojiList = ref([])

    async function pickEmoji() {
      // if (Capacitor.getPlatform() === 'web') {
      //   for (let i = 1; i <= 49; i++) {
      //     let testEmojiUrl = `../assets/emoji/${i}.jpg`
      //     const newEmoji = handlePickedImage(testEmojiUrl)
      //     emojiList.value.push(newEmoji)
      //     console.log('导入后的数组：', emojiList.value)
      //   }
      //   return
      // }
      try {
        const image = await Camera.getPhoto({
          quality: 90,
          source: "PHOTOS", // 指定从相册选择
          resultType: "uri" // 返回文件URI
        })

        // 获取文件路径
        const imageUrl = image.webPath
        console.log("Selected image URI:", imageUrl)
        //转为长期地址
        const base64Url = await blobUrlToBase64(imageUrl)

        // 存入pinia
        const newEmoji = handlePickedImage(base64Url)
        emojiList.value.push(newEmoji)
        console.log('导入后的数组：', emojiList.value)

        //更新全部分类
        useCategoryStore().initAllCat()
      } catch (error) {
        console.error("Error picking image:", error)
      }
    }

    async function blobUrlToBase64(blobUrl) {
      try {
          const response = await fetch(blobUrl);
          if (!response.ok) {
              throw new Error(`请求失败，状态码: ${response.status}`);
          }
          const blob = await response.blob();
          return new Promise((resolve, reject) => {
              const reader = new FileReader();
              reader.readAsDataURL(blob);
              reader.onload = () => {
                  const base64String = reader.result;
                  resolve(base64String);
              };
              reader.onerror = () => {
                  reject(new Error('读取 Blob 时发生错误'));
              };
          });
      } catch (error) {
          console.error('转换出错:', error);
          return null;
      }
  }

    async function readEmojiList() {
      console.log(emojiList.value)
      return emojiList.value
    }

    function selectEmojiById(id) {
      emojiList.value.forEach((item, index) => {
        if (id === item.id) {
          return item;
        }
      })
      return 0;
    }

    function handlePickedImage(imageUrl) {
      // 计算新ID
      const newId = emojiList.value.length === 0
        ? 0
        : Math.max(...emojiList.value.map(e => e.id)) + 1;

      // 创建新对象
      const newEmoji = {
        id: newId,
        url: imageUrl,
        keywords: []
      };

      return newEmoji;
    }

    function deleteAllEmoji(){
      emojiList.value = []
    }

    return { emojiList, pickEmoji, readEmojiList, selectEmojiById ,deleteAllEmoji}
  },
  // 持久化配置（第三个参数）
  {
    persist: {
      key: 'pinia-emoji', // 自定义 localStorage 的 key
      paths: ['emojiList'] // 需要持久化的字段
    }
  }
)